package com.imhouxy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
import java.util.ResourceBundle;

public class App 
{
    public static void main( String[] args ) throws Exception {
        File file = new File("datasource.properties");
        if(!file.exists()){
            FileOutputStream fos = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(fos);
            pw.println("jdbc.driver=com.mysql.jdbc.Driver" );
            pw.println("jdbc.url=jdbc:mysql://127.0.0.1:3306/mysql" );
            pw.println("jdbc.user=root" );
            pw.println("jdbc.pwd=123456" );
            pw.flush();
            pw.close();
            System.exit(0);
        }
        List<DbTable> sourceDb = getTables("datasource.properties");
        for (DbTable table:sourceDb){
            for (DbColumn col :table.getColList()){
                System.out.println(String.format("%s:%s:%s(%s)",table.getTableName(),col.getColumnName(),col.getColumnType(),col.getColumnSize()));
            }
        }
    }

    private static List<DbTable> getTables(String propreties)  throws Exception{

        FileInputStream inputStream = new FileInputStream(propreties);
        ResourceBundle res = new PropertyResourceBundle(inputStream);
        //ResourceBundle res = ResourceBundle.getBundle(propreties);
        List<DbTable> tableList = new ArrayList<>();
        Class.forName(res.getString("jdbc.driver"));
        String url=res.getString("jdbc.url");
        String user=res.getString("jdbc.user");
        String password=res.getString("jdbc.pwd");

        Connection con = getConnection(url, user, password);
        DatabaseMetaData metaDB=con.getMetaData();
        ResultSet rs=metaDB.getTables(null,"%","%", new   String[]{"TABLE"});//获取所有表
        while (rs.next()){
            String  tableName = rs.getString("TABLE_NAME");
            DbTable table = new DbTable(tableName);
            tableList.add(table);
            generatorColumns(metaDB,table);
        }
        return tableList;
    }

    private static void generatorColumns(DatabaseMetaData metaDB,DbTable table) throws SQLException {
        ResultSet rs=metaDB.getColumns(null, "%", table.getTableName(), "%");//获取列名
        while(rs.next()){
            String cname=rs.getString("COLUMN_NAME");
            String ctype=rs.getString("TYPE_NAME");//获取数据类型
            String size = rs.getString("COLUMN_SIZE");//获取数据类型
            DbColumn col = new DbColumn(cname,ctype,size);
            table.getColList().add(col);
        }
    }

    private static Connection getConnection(String url, String user, String password) throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }
}
